const app = getApp();
Page({
  data: {
    currentTab: "all",
    top: 0,
    bg2Img: app.getImgUrl("bg2.webp"),
    logo2Img: app.getImgUrl("logo2.png"),
    logo3Img: app.getImgUrl("logo3.png"),
    repairIconImg: app.getImgUrl("repair-icon.png"),
    recordIconImg: app.getImgUrl("record-icon.png"),
    placeholder1Img: app.getImgUrl("placeholder1.png"),
    kong: app.getImgUrl("kong.png"),
    page: 1,
    needtj: 1,
    listData: [],
    isLoading: false,
    hasMore: true,
    querytype: null,
  },
  formatTimestamp(timestamp) {
    // 秒级时间戳转毫秒级
    const date = new Date(timestamp * 1000);

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  },
  statusFilter(status) {
    const statusMap = {
      0: '待处理',
      2: '已完成',
      3: '已取消'
    };
    console.log(status)
    return statusMap[status] || '未知状态';
  },
  onReady() {
    this.calcHeaderTop();
  },

  onShow() {
    this.calcHeaderTop();
    this.loadData();    // 首次加载数据
  },
  // onLoad() {
  //   this.loadData();    // 首次加载数据
  // },

  // 上拉触底事件处理函数
  onReachBottom() {
    if (!this.data.isLoading && this.data.hasMore) {
      this.loadData();
    }
  },

  // 加载数据方法
  async loadData() {
    console.log(this.data.isLoading)
    console.log(!this.data.hasMore)
    if (this.data.isLoading || !this.data.hasMore) return;

    this.setData({ isLoading: true });

    // wx.showLoading({ title: '加载中...' });

    // 模拟API请求
    let res = await app.axios(
      'workOrder',
      {
        op: "ajaxCusWorkOrderList",
        "needtj": this.data.needtj,
        page: this.data.page,
        querytype: this.data.querytype
      },
      false
    )
    const newData = res.lists.map(items => {
      items.timename = this.formatTimestamp(items.addtime)
      items.statusname = this.statusFilter(items.status)
      console.log('11' + items.statusname + '11')
      return items
    }) || [];
    const total = res.allnum || 0;

    this.setData({
      datas: res.cominfo,
      listData: [...this.data.listData, ...newData],
      page: this.data.page + 1,
      hasMore: this.data.listData.length + newData.length < total
    });
  },
  fail: (err) => {
    wx.showToast({ title: '加载失败', icon: 'none' });
  },
  complete: () => {
    this.setData({ isLoading: false });
    wx.hideLoading();
  },



  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      listData: [],
      page: 1,
      hasMore: true
    });
    this.loadData();
    wx.stopPullDownRefresh();
  },

  calcHeaderTop() {
    // 获取header 部分的高度
    const query = wx.createSelectorQuery();
    query
      .select("#header")
      .boundingClientRect((rect) => {
        if (!rect) {
          return;
        }
        const headerHeight = rect.height;

        // header 高度 + 状态栏高度 + 标题栏高度
        const totalHeight =
          headerHeight + wx.getWindowInfo().statusBarHeight + 44;

        this.setData({
          top: totalHeight,
        });
      })
      .exec();
  },

  onTabChange(e) {
    if (e.currentTarget.dataset.tab == 'all') {
      // 全部
      this.setData({ querytype: null });
    }
    if (e.currentTarget.dataset.tab == 'pending') {
      // 待处理
      this.setData({ querytype: 0 });
    }
    if (e.currentTarget.dataset.tab == 'processing') {
      // 服务中
      this.setData({ querytype: 1 });
    }
    if (e.currentTarget.dataset.tab == 'completed') {
      // 已完成
      this.setData({ querytype: 2 });
    }

    this.setData({
      currentTab: e.currentTarget.dataset.tab,
      listData: [],
      page: 1,
      hasMore: true,
      isLoading: false
    });

    this.loadData();
  },
  viewDetailLog(e) {
    console.log(e.currentTarget.dataset.item.exusername)
    console.log("id=" + e.currentTarget.dataset.item.id + "&exusername=" + e.currentTarget.dataset.item.exusername)
    wx.navigateTo({
      url: "/pages/client/execute_log/index?id=" + e.currentTarget.dataset.item.id + "&exusername=" + e.currentTarget.dataset.item.exusername,
    });
  },

  /**
   * 快速报修
   */
  goRepairPage() {
    wx.navigateTo({
      url: "/pages/client/fault_list/index",
    });
  },

  /**
   * 维护记录
   */
  goRecordPage() {
    wx.navigateTo({
      url: "/pages/device/recordList/index",
    });
  },
});
